/* ---------------------------------------------------------------------------------------------
 *
 *            Capital Alliance Software Confidential Proprietary
 *            (c) Copyright CAS 201{x}, All Rights Reserved
 *                          www.pekall.com
 *
 * ----------------------------------------------------------------------------------------------
 */

package com.pekall.todo;

import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import com.pekall.todo.model.ToDoTasks;
import com.pekall.todo.util.SQLiteOperate;
import com.pekall.todo.util.ShareUtil;

/**
 * 待办事件List
 * 
 * @author LeiKang
 */
public class HomeScreen extends Activity implements OnClickListener {

    private static final int STATE_COMPLETE = 1;

    private static final int STATE_UNCOMPLETE = 0;

    private static final int LEVEL_LOW = 0;

    private static final int LEVEL_MID = 1;

    private static final int LEVEL_HIGH = 2;

    private String[] items = new String[] {
            "优先级", "名称", "最后修改时间"
    };

    private ImageButton mNewWork;

    // private ImageButton mCheckout;
    private Intent mIntent;

    private ToDoTasks mToDoTasks;

    private ListView mWorkList;

    private ListAdapter mAdapter;

    private List<ToDoTasks> toDotaskses;

    private LayoutInflater mLayoutInflater;

    private SQLiteOperate sql;

    private Context mContext;

    private ShareUtil shareUtil;

    /* =========================== activity ======================= */
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        mContext = this;
    }

    // 刷新listview
    private void reflash() {
        if (toDotaskses.size() == 0) {
            setContentView(R.layout.homeempty);
        } else {
            setContentView(R.layout.homescreen);
            mWorkList = (ListView) findViewById(R.id.worklist);
            mAdapter = new ListAdapter(this, toDotaskses);
            mWorkList.setAdapter(mAdapter);
            mWorkList.setOnItemClickListener(new OnItemClickListener() {
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    Intent mIntent = new Intent(mContext, MainScreen.class);
                    mIntent.putExtra("todotasks_key", toDotaskses.get(position));
                    startActivity(mIntent);
                    overridePendingTransition(R.anim.fade, R.anim.hold);
                }
            });
        }
    }

    /*
     * (non-Javadoc)
     * @see android.app.Activity#onResume()
     */
    @Override
    protected void onResume() {
        super.onResume();
        sql = new SQLiteOperate(this);
        shareUtil = new ShareUtil(this);
        // 默认按最后修改时间排序
        toDotaskses = sql.loadAll(shareUtil.getInt("sort_key"));
        reflash();
        mNewWork = (ImageButton) findViewById(R.id.newButton);
        mNewWork.setOnClickListener(this);
        // mCheckout = (ImageButton) findViewById(R.id.checkout);
        // mCheckout.setOnClickListener(this);
    }

    public void onClick(View v) {
        if (v.getId() == R.id.newButton) {
            mToDoTasks = new ToDoTasks();
            mIntent = new Intent(this, MainScreen.class);
            mIntent.putExtra("todotasks_key", mToDoTasks);
            startActivity(mIntent);
        }
        // else if (v.getId() == R.id. newButton) {
        // this.finish();
        // }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        menu.add(0, Menu.FIRST, Menu.NONE, R.string._addNew).setIcon(
                R.drawable.cmcc_icon_all_reverse_choose);
        menu.add(0, Menu.FIRST + 1, Menu.NONE, R.string._sort)
                .setIcon(R.drawable.cmcc_name_sorting);
        menu.add(0, Menu.FIRST + 2, Menu.NONE, R.string._delete).setIcon(R.drawable.cmcc_icon_del);
        return true;
    }

    @SuppressWarnings("unchecked")
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        super.onOptionsItemSelected(item);
        switch (item.getItemId()) {

            case Menu.FIRST:
                mToDoTasks = new ToDoTasks();
                mIntent = new Intent(this, MainScreen.class);
                mIntent.putExtra("todotasks_key", mToDoTasks);
                startActivity(mIntent);
                break;

            case Menu.FIRST + 1:
                if (toDotaskses.size() == 0) {
                    Toast.makeText(this, R.string._no_tasks, Toast.LENGTH_SHORT).show();
                    break;
                }
                new AlertDialog.Builder(this).setTitle(R.string._sort).setIcon(
                        android.R.drawable.ic_dialog_info).setSingleChoiceItems(items, 0,
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                sql = new SQLiteOperate(mContext);
                                toDotaskses = sql.loadAll(which);
                                reflash();
                                shareUtil.saveSortKeyValue(which);
                                dialog.dismiss();
                            }
                        }).setNegativeButton(R.string._cancle, null).show();
                break;

            case Menu.FIRST + 2:
                if (toDotaskses.size() == 0) {
                    Toast.makeText(this, R.string._no_tasks, Toast.LENGTH_SHORT).show();
                    break;
                }
                mIntent = new Intent(this, DeleteScreen.class);
                mIntent.putParcelableArrayListExtra("todotasks_key",
                        (ArrayList<? extends Parcelable>) toDotaskses);
                startActivity(mIntent);
                break;
        }

        return true;

    }

    /* ====================== adapter ======================= */
    public class ListAdapter extends BaseAdapter {
        private List<ToDoTasks> mToDotaskses;

        private Context mContext;

        private ListAdapter(Context context, List<ToDoTasks> toDotaskses) {
            mContext = context;
            mLayoutInflater = (LayoutInflater) mContext
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            mToDotaskses = toDotaskses;

        }

        public int getCount() {
            return mToDotaskses.size();
        }

        public Object getItem(int position) {
            return mToDotaskses.get(position);
        }

        public long getItemId(int position) {
            return position;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = mLayoutInflater.inflate(R.layout.events_item, null);
            }
            final LinearLayout linearLayout = (LinearLayout) convertView;
            final ImageView stateIcon = (ImageView) linearLayout.findViewById(R.id.stateIcon);
            final TextView eventTitle = (TextView) linearLayout.findViewById(R.id.eventTitle);
            final ImageView levelIcon = (ImageView) linearLayout.findViewById(R.id.levelIcon);
            final int state = mToDotaskses.get(position).getState();
            final int type = mToDotaskses.get(position).getType();
            if (state == STATE_COMPLETE) {
                stateIcon.setImageResource(R.drawable.cmcc_list_completed);
                levelIcon.setImageDrawable(null);
            } else if (state == STATE_UNCOMPLETE) {
                stateIcon.setImageResource(R.drawable.cmcc_todolist_uncompleted);
                if (type == LEVEL_LOW)
                    levelIcon.setImageResource(R.drawable.cmcc_list_priority_low);
                else if (type == LEVEL_MID)
                    levelIcon.setImageResource(R.drawable.cmcc_list_priority_medium);
                else if (type == LEVEL_HIGH)
                    levelIcon.setImageResource(R.drawable.cmcc_list_priority_high);
            }
            eventTitle.setText(mToDotaskses.get(position).getTitle());
            return linearLayout;
        }
    }

}
